package com.shen.blogadmin.service;

import com.shen.blogadmin.pojo.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

@Service
public class SecurityUserService implements UserDetailsService {

    @Autowired
    AdminService adminService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //登录的时候，会把Username 传递到这里
        //通过username查询admin表 如果admin存在 将密码告诉我们的spring security
        //如果不存在 返回null 认证失败
        Admin adminByUsername = adminService.findAdminByUsername(username);
        if (adminByUsername == null){
            //认证失败
            return null;
        }
        //User 是spring security的
        UserDetails userDetails =  new User(username,adminByUsername.getPassword(),new ArrayList<>());
        return userDetails;
    }
}
